package com.mybed.crm.interceptor;

import com.mybed.crm.utils.jwt.JwtUtil;
import com.mybed.crm.utils.thread.UserThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取令牌
        String s = request.getHeader("Cookie");
        if(s==null||"Admin-Token=undefined".equals(s)){
            log.info("token异常,{}",s);
            //4、不通过，响应401状态码
            response.setStatus(200);
            return false;
        }
        String token = s.substring("Admin-Token=".length());
        String clientIp = request.getHeader("X-Real-IP");
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("X-Forwarded-For");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        log.info("登入的Ip,{}",clientIp);
        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT("43a416fa9c9b453b61175713074324c3",token);
            String userId = claims.get("userId").toString();
            log.info("当前前端用户id：{}", userId);
            //3、通过，放行
            UserThreadLocalUtil.setUser(userId);
            return true;
        } catch (Exception ex) {
            log.info("token异常");
            //4、不通过，响应401状态码
            response.setStatus(200);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtil.clear();
    }
}
